package com.jeeplus.modules.web.web;

import com.jeeplus.common.beanvalidator.BeanValidators;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.DataEntity;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.web.entity.YjMahjongHall;
import com.jeeplus.modules.web.entity.YjMahjongHallRoom;
import com.jeeplus.modules.web.entity.YjMahjongHallSalesman;
import com.jeeplus.modules.web.entity.YjMahjongHallWaiters;
import com.jeeplus.modules.web.service.YjMahjongHallRoomService;
import com.jeeplus.modules.web.service.YjMahjongHallService;
import com.jeeplus.modules.web.service.YjMahjongHallWaitersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 棋牌室Controller
 * @author liangbing
 * @version 2021-03-11
 */
@Api(value = "YjMahjongHallController", description = "棋牌室控制器")
@Controller
@RequestMapping(value = "${adminPath}/web/yjMahjongHall")
public class YjMahjongHallController extends BaseController {
    @Autowired
    private YjMahjongHallService yjMahjongHallService;

    @Autowired
    private YjMahjongHallRoomService yjMahjongHallRoomService;

    @Autowired
    private YjMahjongHallWaitersService yjMahjongHallWaitersService;

    @ModelAttribute
    public YjMahjongHall get(@RequestParam(required=false) String id) {
        YjMahjongHall entity = null;
        if (StringUtils.isNotBlank(id)){
            entity = yjMahjongHallService.get(id);

            // 拆分省市区region
            String region = entity.getRegion();
            if (StringUtils.isNotBlank(region)) {
                String[] parts = region.split(" ");
                if (parts.length >= 3) {
                    entity.setProvince(parts[0]);
                    entity.setCity(parts[1]);
                    entity.setDistrict(parts[2]);
                }
            }
        }
        if (entity == null){
            entity = new YjMahjongHall();
        }
        return entity;
    }

    /**
     * 棋牌室列表页面
     */
    @RequiresPermissions("web:yjMahjongHall:list")
    @RequestMapping(value = {"list", ""})
    public String list() {
        return "modules/web/yjMahjongHallList";
    }

    /**
     * 棋牌室列表数据
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHall:list")
    @RequestMapping(value = "data")
    public Map<String, Object> data(YjMahjongHall yjMahjongHall, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<YjMahjongHall> page = yjMahjongHallService.findPage(new Page<YjMahjongHall>(request, response), yjMahjongHall);
        return getBootstrapData(page);
    }

    /**
     * 查看，增加，编辑棋牌室表单页面
     */
    @RequiresPermissions(value={"web:yjMahjongHall:view","web:yjMahjongHall:add","web:yjMahjongHall:edit"},logical= Logical.OR)
    @RequestMapping(value = "form")
    public String form(YjMahjongHall yjMahjongHall, Model model) {
        model.addAttribute("yjMahjongHall", yjMahjongHall);
        if(StringUtils.isBlank(yjMahjongHall.getId())){//如果ID是空为添加
            model.addAttribute("isAdd", true);
            model.addAttribute("isOpenCall", 0);
        } else {
            model.addAttribute("isOpenCall", new Integer(1).equals(yjMahjongHall.getIsOpenCall()) ? 1 : 0);
        }
        return "modules/web/yjMahjongHallForm";
    }

    /**
     * 保存棋牌室
     */
    @RequiresPermissions(value={"web:yjMahjongHall:add","web:yjMahjongHall:edit"},logical=Logical.OR)
    @RequestMapping(value = "save")
    public String save(YjMahjongHall yjMahjongHall, Model model, RedirectAttributes redirectAttributes) throws Exception {
        if (!beanValidator(model, yjMahjongHall)){
            return form(yjMahjongHall, model);
        }

        //省市区
        if (StringUtils.isNotBlank(yjMahjongHall.getProvince()) && StringUtils.isNotBlank(yjMahjongHall.getCity()) && StringUtils.isNotBlank(yjMahjongHall.getDistrict())) {
            StringBuffer regionSb = new StringBuffer();
            regionSb.append(yjMahjongHall.getProvince()).append(" ");
            regionSb.append(yjMahjongHall.getCity()).append(" ");
            regionSb.append(yjMahjongHall.getDistrict());

            yjMahjongHall.setRegion(regionSb.toString());
        }

        // 重复性检查：根据名称和手机来检查是否已经创建过了
        boolean isDuplicate = checkDuplicate(yjMahjongHall);
        if (isDuplicate) {
            addMessage(model, "保存失败！该棋牌室已经创建过");
            return form(yjMahjongHall, model);
        }

        // 是否开通呼叫
        if ("on".equals(yjMahjongHall.getIsOpenCallVal())) {
            yjMahjongHall.setIsOpenCall(1);
        } else {
            yjMahjongHall.setIsOpenCall(0);
        }

        //新增或编辑表单保存
        yjMahjongHallService.save(yjMahjongHall);//保存
        addMessage(redirectAttributes, "保存棋牌室成功");
        return "redirect:"+ Global.getAdminPath()+"/web/yjMahjongHall/?repage";
    }

    /**
     * 删除棋牌室
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHall:del")
    @RequestMapping(value = "delete")
    public AjaxJson delete(YjMahjongHall yjMahjongHall, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        yjMahjongHallService.delete(yjMahjongHall);
        j.setMsg("删除棋牌室成功");
        return j;
    }

    /**
     * 批量删除棋牌室
     */
    @ResponseBody
    @RequiresPermissions("web:yjMahjongHall:del")
    @RequestMapping(value = "deleteAll")
    public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
        AjaxJson j = new AjaxJson();
        String idArray[] =ids.split(",");
//        for(String id : idArray){
//            yjMahjongHallService.delete(yjMahjongHallService.get(id));
//        }

        yjMahjongHallService.batchDeleteLogic(Arrays.asList(idArray));
        j.setMsg("删除棋牌室成功");
        return j;
    }

    /**
     * 微信端新建棋牌室
     * @param paramYjMahjongHall 棋牌室实体
     * @return
     */
    @ApiOperation(notes = "createMahjongHall", httpMethod = "POST", value = "微信端新建棋牌室")
    @ResponseBody
    @PostMapping(value = "createMahjongHall")
    public AjaxJson createMahjongHall(@RequestBody @Validated YjMahjongHall paramYjMahjongHall, BindingResult result) {
        // 检查参数
        BeanValidators.validateWithException(validator, paramYjMahjongHall);

        AjaxJson j = new AjaxJson();

        // 特殊参数检查
        if (StringUtils.isBlank(paramYjMahjongHall.getOpenid())) {
            j.setSuccess(false);
            j.setMsg("业务员不能为空");
            return j;
        }

        if (StringUtils.isBlank(paramYjMahjongHall.getSalesmanPhone())) {
            j.setSuccess(false);
            j.setMsg("业务员手机号不能为空");
            return j;
        }

        if (StringUtils.isBlank(paramYjMahjongHall.getRegion())) {
            j.setSuccess(false);
            j.setMsg("省市区不能为空");
            return j;
        }

        // 重复性检查：根据名称和手机来检查是否已经创建过了
        boolean isDuplicate = checkDuplicate(paramYjMahjongHall);
        if (isDuplicate) {
            j.setSuccess(false);
            j.setMsg("该馆已经创建过");
            return j;
        }

        //新增棋牌室
        paramYjMahjongHall.setCreateDate(new Date());
        yjMahjongHallService.save(paramYjMahjongHall);//保存

        j.setSuccess(true);
        j.setMsg("棋牌室创建成功！");
        j.getBody().put("data", paramYjMahjongHall);
        return j;
    }

    /**
     * 微信端保存棋牌室 支持新增和编辑
     * @param paramYjMahjongHall 棋牌室实体
     * @return
     */
    @ApiOperation(notes = "saveMahjongHall", httpMethod = "POST", value = "微信端保存棋牌室")
    @ResponseBody
    @PostMapping(value = "saveMahjongHall")
    public AjaxJson saveMahjongHall(@RequestBody @Validated YjMahjongHall paramYjMahjongHall, BindingResult result) {
        // 检查参数
        BeanValidators.validateWithException(validator, paramYjMahjongHall);

        AjaxJson j = new AjaxJson();

        // 特殊参数检查
        if (StringUtils.isBlank(paramYjMahjongHall.getOpenid())) {
            j.setSuccess(false);
            j.setMsg("业务员不能为空");
            return j;
        }

        // 业务员手机号
        if (StringUtils.isBlank(paramYjMahjongHall.getSalesmanPhone())) {
            j.setSuccess(false);
            j.setMsg("业务员手机号不能为空");
            return j;
        }

        if (StringUtils.isBlank(paramYjMahjongHall.getRegion())) {
            j.setSuccess(false);
            j.setMsg("省市区不能为空");
            return j;
        }

        // 重复性检查：根据名称和手机来检查是否已经创建过了
        boolean isDuplicate = checkDuplicate(paramYjMahjongHall);
        if (isDuplicate) {
            j.setSuccess(false);
            j.setMsg("该馆已经创建过");
            return j;
        }

        //保存棋牌室 新增或者编辑，取决于有无id
        paramYjMahjongHall.setCreateDate(new Date());
        yjMahjongHallService.save(paramYjMahjongHall);//保存

        j.setSuccess(true);
        j.setMsg("棋牌室保存成功！");
        j.getBody().put("data", paramYjMahjongHall);
        return j;
    }

    /**
     * 微信端获取业务员创建的棋牌室列表
     * @param salesmanPhone 业务员手机号
     * @param searchText 搜索内容 棋牌室名称、联系人、联系人手机号
     * @param dateLevel 日期级别 1-当天 2-近7天内 3-近30天 4-本月 5-本季度
     * @return
     */
    @ApiOperation(notes = "mahjongHallsList", httpMethod = "GET", value = "微信端获取棋牌室列表")
    @ResponseBody
    @GetMapping(value = "mahjongHallsList")
    @ApiImplicitParams({ @ApiImplicitParam(name = "salesmanPhone", value = "salesmanPhone", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "searchText", value = "searchText", required = false, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "dateLevel", value = "dateLevel", required = false, paramType = "query",dataType = "string")})
    public AjaxJson mahjongHallsList(@NotBlank String salesmanPhone, String searchText, String dateLevel) {
        AjaxJson j = new AjaxJson();

        // 参数检查
        if (StringUtils.isBlank(salesmanPhone)) {
            j.setSuccess(false);
            j.setMsg("业务员手机号不能为空");
            return j;
        }

        if (StringUtils.isNotEmpty(searchText)) {
            searchText = searchText.trim();
        }
        List<YjMahjongHall> hallsList = yjMahjongHallService.findListBySearchTextAndDateLevel(salesmanPhone, searchText, dateLevel);
        j.getBody().put("data", hallsList);
        return j;
    }

    /**
     * 微信端获取业务员创建的棋牌室个数和房间的个数信息
     * @param salesmanPhone 业务员手机号
     * @param searchText 搜索内容 棋牌室名称、联系人、联系人手机号
     * @param dateLevel 日期级别 1-当天 2-近7天内 3-近30天 4-本月 5-本季度
     * @return
     */
    @ApiOperation(notes = "mahjongHallsCount", httpMethod = "GET", value = "微信端获取业务员创建的棋牌室个数和房间的个数信息")
    @ResponseBody
    @GetMapping(value = "mahjongHallsCount")
    @ApiImplicitParams({@ApiImplicitParam(name = "salesmanPhone", value = "salesmanPhone", required = true, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "searchText", value = "searchText", required = false, paramType = "query",dataType = "string"),
            @ApiImplicitParam(name = "dateLevel", value = "dateLevel", required = false, paramType = "query",dataType = "string")})
    public AjaxJson mahjongHallsCount(@NotBlank String salesmanPhone, String searchText, String dateLevel) {
        AjaxJson j = new AjaxJson();

        // 参数检查
        if (StringUtils.isBlank(salesmanPhone)) {
            j.setSuccess(false);
            j.setMsg("业务员手机号不能为空");
            return j;
        }

        if (StringUtils.isNotEmpty(searchText)) {
            searchText = searchText.trim();
        }
        List<YjMahjongHall> hallsList = yjMahjongHallService.findListBySearchTextAndDateLevel(salesmanPhone, searchText, dateLevel);

        YjMahjongHallSalesman hallSalesman = new YjMahjongHallSalesman();
        //hallSalesman.setMahjongHallsList(hallsList);
        hallSalesman.setHallsCount(hallsList.size());

        // 房间数
        AtomicReference<Integer> totalRooms = new AtomicReference<>(0);
        hallsList.stream().forEach(item -> {
            Integer rooms = item.getRooms();

            if (rooms == null){
                rooms = 0;
            }

            Integer finalRooms = rooms;
            totalRooms.updateAndGet(v -> v + finalRooms);
        });

        hallSalesman.setRoomsCount(totalRooms.get());

        j.getBody().put("data", hallSalesman);
        return j;
    }

    /**
     * 微信端获取棋牌室详情
     * @param hallId
     * @return
     */
    @ApiOperation(notes = "mahjongHallInfo", httpMethod = "GET", value = "微信端获取棋牌室详情")
    @ResponseBody
    @GetMapping(value = "mahjongHallInfo")
    @ApiImplicitParams({@ApiImplicitParam(name = "hallId", value = "hallId", required = true, paramType = "query",dataType = "string")})
    public AjaxJson mahjongHallInfo(@NotBlank String hallId) {
        AjaxJson j = new AjaxJson();

        YjMahjongHall record = new YjMahjongHall();
        record.setId(hallId);

        // 棋牌室信息
        YjMahjongHall dbRecord = yjMahjongHallService.get(record);
        if (dbRecord == null) {
            j.setSuccess(false);
            j.setMsg("棋牌室信息不存在");
            return j;
        }

        // 房间信息
        YjMahjongHallRoom roomRecord = new YjMahjongHallRoom();
        roomRecord.setMahjongHall(record);
        List<YjMahjongHallRoom> hallRoomsList = yjMahjongHallRoomService.findList(roomRecord);
        if (hallRoomsList == null) {
            hallRoomsList = new ArrayList<>();
        }
        dbRecord.setMahjongHallRoomList(hallRoomsList);

        // 服务生信息
        YjMahjongHallWaiters waitersRecord = new YjMahjongHallWaiters();
        waitersRecord.setMahjongHall(record);
        List<YjMahjongHallWaiters> hallWaitersList = yjMahjongHallWaitersService.findList(waitersRecord);
        if (hallWaitersList == null) {
            hallWaitersList = new ArrayList<>();
        }
        dbRecord.setMahjongHallWaitersList(hallWaitersList);

        // 返回消息
        j.getBody().put("data", dbRecord);
        return j;
    }

    /**
     * 微信端删除棋牌室
     * @param hallId
     * @return 删除结果
     */
    @ApiOperation(notes = "deleteMahjongHall", httpMethod = "DELETE", value = "微信端删除棋牌室")
    @ResponseBody
    @DeleteMapping(value = "deleteMahjongHall")
    @ApiImplicitParams({@ApiImplicitParam(name = "hallId", value = "hallId", required = true, paramType = "query",dataType = "string")})
    public AjaxJson deleteMahjongHall(@NotBlank String hallId) {
        AjaxJson j = new AjaxJson();

        YjMahjongHall record = new YjMahjongHall();
        record.setId(hallId);

        // 棋牌室信息
        YjMahjongHall dbRecord = yjMahjongHallService.get(record);
        if (dbRecord == null) {
            j.setSuccess(false);
            j.setMsg("棋牌室信息不存在");
            return j;
        }

        if (DataEntity.DEL_FLAG_DELETE.equals(dbRecord.getDelFlag())) {
            j.setSuccess(false);
            j.setMsg("棋牌室已被删除");
            return j;
        }

        yjMahjongHallService.deleteByLogic(dbRecord);

        // 返回消息
        j.setMsg("删除棋牌室成功！");
        return j;
    }

    /**
     * 重复性检查 根据名称和手机来检查是否已经创建过了
     * @param yjMahjongHall
     * @return
     */
    private boolean checkDuplicate(YjMahjongHall yjMahjongHall) {
        YjMahjongHall record = new YjMahjongHall(yjMahjongHall.getName(), yjMahjongHall.getMobile());

        if (StringUtils.isNotBlank(yjMahjongHall.getId())) {
            record.setId(yjMahjongHall.getId());
        }

        return yjMahjongHallService.isDuplicate(record);
    }
}
